//
//  TSCVCCreateShopSearchMall.m
//  Tsc_IOS
//
//  Created by Rio on 15-6-3.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCCreateShopSearchMall.h"
#import "TSCConstants.h"
#import "TSCMyUIUtil.h"
#import "TSCMyAutoCompleteSearchBar.h"
#import "TSCMyNetworkUtil.h"
#import "TSCMyUtil.h"
#import "TSCMyHttpUtil.h"
#import "TSCJsonMall.h"
#import "TSCVCSelectMall.h"
#import "TSCMyNaviBarCreator.h"

@interface TSCVCCreateShopSearchMall () {
    // 输入项
    NSInteger _iCityId;
    
    TSCMyAutoCompleteSearchBar * _sbMallName;
}

@end

@implementation TSCVCCreateShopSearchMall

#pragma mark 获取并校验输入
- (void) getVCInput:(NSNotificationCenter *)notification {
    [super getVCInput:notification];
    
    _iCityId = [[_inputDic objectForKey:AEKI_CITY_ID] intValue];
    
    NSAssert(_iCityId != 0, @"%s: 输入参数必须包括：%@！", __FUNCTION__, AEKI_CITY_ID);
}

+ (id) vcCreateShopSearchMallWithStoryBoard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_CREATE_SHOP_SEARCH_MALL];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:YES goBackVC:nil hasAppLogo:YES titleResourceKey:@"title_search_mall" iconResourceNameArray:nil iconClickedListenerArray:nil];
    
    // ===== 初始化UI
    
    // 获得nvb的frame
    CGRect nvbRect = self.navigationController.navigationBar.frame;
    CGRect statusBarRect = [[UIApplication sharedApplication] statusBarFrame];
    
    // 初始化SearchBar
    _sbMallName = [[TSCMyAutoCompleteSearchBar alloc]init];
    _sbMallName.placeholder = NSLocalizedString(@"hint_input_mall_name", nil);
    [self.view addSubview:_sbMallName];
    
    // 添加约束
    // SearchBar
    _sbMallName.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%f-[_sbMallName]-%f-|", UI_SCREEN_PADDING, UI_SCREEN_PADDING] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sbMallName)]]; // left+right
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[_sbMallName(%f)]", (UI_SCREEN_PADDING + nvbRect.size.height + statusBarRect.size.height), UI_SEARCH_BAR_HEIGHT] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_sbMallName)]];
    
    // 设置SearchBar单元格创建方式
    __weak typeof (self) _weakSelf = self;
    _sbMallName.cellCreator = ^(UITableView * tableView, NSIndexPath * indexPath) {
        typeof (self) _strongSelf = _weakSelf;
        
        UITableViewCell *cell = nil;
        if (_strongSelf) {
            static NSString *cellReuseId = @"textCell";
            cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseId];
                cell.backgroundColor = COLOR_MT_SPINNER_CELL_BG;
            }
            NSUInteger row = [indexPath row];
            TSCJsonMall * mallJson = [_strongSelf->_sbMallName.dataArray objectAtIndex:row];
            NSString * text = mallJson.name;
            if ([text isKindOfClass:[NSString class]] == NO) {
                NSLog(@"[W]%s: MyAutoCompleteSearchBar数据源中，存在不是NSString类型的数据！显示时将抛出异常！数据源中的对象：%@", __FUNCTION__, text);
                
                // 设置为错误提示
                text = @"数据源类型不是NSString！";
            }
            
            cell.textLabel.text = text;
            return cell;
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
            return cell;
        }
    };
    
    // 注册事件——搜索栏字数变化时
    // 当非自动补全、有网络连接、且用户开始输入时，从服务器获取自动补全提示
    _sbMallName.textDidChangeListener = ^(UISearchBar * searchBar, NSString * searchText) {
        typeof (self) _strongSelf = _weakSelf;
        
        if (_strongSelf) {
            NSString * mallName = [TSCMyUtil trim:_strongSelf->_sbMallName.text];
            if ([_strongSelf->_sbMallName isPerformingCompletion] == NO
                && [TSCMyNetworkUtil checkNetwork] == true
                && [TSCMyUtil isStringEmpty:mallName] == NO) {
                // 为了让AutoComplete的内容能够“平滑”变换，首先将其隐藏，当重新设定完adapter之后，再显示
                [_strongSelf->_sbMallName dismissTable];
                //        _sbMallName.dismissDropDown();
                
                [_strongSelf getAutoCompTip_PP1:mallName];
            }
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
        }
    };
    
    // 注册事件——点击自动提示项后，自动选择并返回上一步
    _sbMallName.itemSelectedListener = ^(NSIndexPath * ip) {
        typeof (self) _strongSelf = _weakSelf;
        
        if (_strongSelf) {
            [[_strongSelf navigationController]popViewControllerAnimated:YES];
            
            // 找到上一个vc（应该是CreateShopGatherInfo）
            NSArray * vcArray = [_strongSelf navigationController].viewControllers;
            UIViewController * lastVC = [vcArray lastObject];
            
            // VC间传递参数
            TSCJsonMall * selectedMallJson = [_strongSelf->_sbMallName getSelectedObject];
            NSDictionary * inputDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithLong:selectedMallJson.Id], selectedMallJson.name, nil] forKeys:[NSArray arrayWithObjects:AEKI_MALL_ID, AEKI_MALL_NAME, nil]];
            [[NSNotificationCenter defaultCenter]addObserver:lastVC selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_CREATE_SHOP_GATHER_INFO object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_CREATE_SHOP_GATHER_INFO object:inputDic];
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
        }
    };
    
    
    // 注册事件——点击弹出键盘上的搜索按钮时
    NSInteger iCityId = _iCityId;
    _sbMallName.searchBtnClickedListener = ^(UISearchBar * searchBar) {
        typeof (self) _strongSelf = _weakSelf;
        
        if (_strongSelf) {
            NSString * mallName = [TSCMyUtil trim:_strongSelf->_sbMallName.text];
            
            if ([TSCMyUtil isStringEmpty:mallName] == NO) {
                if ([TSCMyNetworkUtil checkNetwork]== true) {
                    // 开启搜索VC
                    TSCVCSelectMall * vcSelectMall = [TSCVCSelectMall vcSelectMallWithStoryboard];
                    [[_strongSelf navigationController] pushViewController:vcSelectMall animated:YES];
                    
                    // VC间传递参数
                    NSMutableDictionary * inputDic = [NSMutableDictionary dictionary];
                    [inputDic setObject:mallName forKey:AEKI_MALL_NAME];
                    [inputDic setObject:[NSNumber numberWithLong:iCityId] forKey:AEKI_CITY_ID];
                    [[NSNotificationCenter defaultCenter]addObserver:vcSelectMall selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_SELECT_MALL object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_SELECT_MALL object:inputDic];
                } else {
                    [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
                }
            } else {
                [TSCMyUIUtil popErrWithResourceKey:@"err_empty_mall_name"];
            }
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
        }
    };
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark 私有方法
/* private */ - (void) getAutoCompTip_PP1:(NSString *)mallName {
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:[_ud objectForKey:UD_USER_ID] forKey:@"user_id"];
    [reqDic setObject:[_ud objectForKey:UD_LOGIN_KEY] forKey:@"login_key"];
    [reqDic setObject:[NSNumber numberWithLong:URL_MATCH_TYPE_PREFIX] forKey:@"match_type"];
    [reqDic setObject:[NSNumber numberWithLong:_iCityId] forKey:@"city_id"];
    [reqDic setObject:mallName forKey:@"name"];
    [reqDic setObject:[NSNumber numberWithLong:0] forKey:@"offset"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_SEARCH_MALL dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default:
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
        }
        
        // 解析服务器返回
        NSArray * contentArray = (NSArray *) contentDictionary; // 注：此时content是Array，不是Dictionary
        NSMutableArray * mallArray = [NSMutableArray array];
        for (NSDictionary * mallDic in contentArray) {
            TSCJsonMall * jsonMall = [[TSCJsonMall alloc]init];
            jsonMall.Id = [[mallDic objectForKey:@"id"] intValue];
            jsonMall.name = [mallDic objectForKey:@"name"];
            [mallArray addObject:jsonMall];
        }
        
        // 继续后续逻辑...
        [self getAutoCompTip_PP2:mallArray];
    }];
}

/* private */ - (void) getAutoCompTip_PP2:(NSArray *)mallArray {
    [_sbMallName prepareData_P1:^{
        _sbMallName.dataArray = [NSMutableArray arrayWithArray:mallArray];
    } completionHandler:^{
        [_sbMallName applyData];
        [_sbMallName showTable];
    }];
}


#pragma mark 收回键盘

/* private */ - (void) resignAllFirstResponder {
    [_sbMallName resignFirstResponder];
}

// return键收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

// 点击空白区域收回键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self resignAllFirstResponder];
}


@end
